package cn.stylefeng.guns.modular.order.service.impl;

import cn.hutool.json.JSONObject;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.core.util.DateUtil;
import cn.stylefeng.guns.core.util.justApi;
import cn.stylefeng.guns.modular.basic.entity.BasicCustomer;
import cn.stylefeng.guns.modular.basic.service.BasicCustomerService;
import cn.stylefeng.guns.modular.hx.order.controller.HxOrderOutController;
import cn.stylefeng.guns.modular.order.controller.OutOrderController;
import cn.stylefeng.guns.modular.order.entity.OrderPutExcelItem;
import cn.stylefeng.guns.modular.order.entity.OutOrder;
import cn.stylefeng.guns.modular.order.mapper.OutOrderMapper;
import cn.stylefeng.guns.modular.order.model.params.OrderTransportParam;
import cn.stylefeng.guns.modular.order.model.params.OutOrderDetailedParam;
import cn.stylefeng.guns.modular.order.model.params.OutOrderParam;
import cn.stylefeng.guns.modular.order.model.result.OrderTransportResult;
import cn.stylefeng.guns.modular.order.model.result.OutOrderDetailedResult;
import cn.stylefeng.guns.modular.order.model.result.OutOrderResult;
import cn.stylefeng.guns.modular.order.service.*;
import cn.stylefeng.guns.modular.replenishment.service.ReplenishmentOrderService;
import cn.stylefeng.guns.modular.storage.model.params.StorageOutParam;
import cn.stylefeng.guns.modular.storage.model.result.StorageOutResult;
import cn.stylefeng.guns.modular.storage.service.StorageOutDetailedService;
import cn.stylefeng.guns.modular.storage.service.StorageOutService;
import cn.stylefeng.guns.modular.storage.service.impl.StorageOutDetailedServiceImpl;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * <p>
 * 聚水潭出库订单
 * </p>
 *
 * @author wp
 * @since 2025-06-09
 */
@Service
public class JSTOutOrderScheduledServiceImpl  implements JSTOutOrderScheduledService {


    private Lock lock = new ReentrantLock();
    @Autowired
    private BasicCustomerService basicCustomerService;
    @Autowired
    private OutOrderService outOrderService ;
    @Autowired
    private UserService userService;
    @Autowired
    private OutOrderDetailedService outOrderDetailedService;
    @Autowired
    private StorageOutService storageOutService;
    @Autowired
    private StorageOutDetailedService storageOutDetailedService;
    @Autowired
    private OrderTransportService orderTransportService;
    @Autowired
    private OutOrderMapper outOrderMapper;
    @Autowired
    private WhOutOrderService whOutOrderService;


    @Autowired
    private ReplenishmentOrderService replenishmentOrderService;
    @Override
    public ResponseData getJSTOutOrder(Long userId,Long customerId) {
            //获取快递订单
            // 获取当前时间
            LocalDateTime now = LocalDateTime.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String modified_end = now.format(formatter);

            // 减去20分钟
            LocalDateTime tenMinutesAgo = now.minus(Duration.ofMinutes(20));
            String modified_begin = tenMinutesAgo.format(formatter);

            User user = userService.getById(userId);
            BasicCustomer byId = basicCustomerService.getById(customerId);
            String justAppsecret = byId.getJustAppsecret();
            String justAppkey = byId.getJustAppkey();
            String accessToken = byId.getAccessToken();

            ResponseData responseData = new ResponseData();

            List<OrderPutExcelItem> list = new ArrayList<OrderPutExcelItem>();
            Integer page_index = 1;//页数
            boolean has_next = true;//是否有下一页
            while (has_next) {
                //只能分页查询，一页最多50条
                //接口调用频率秒级内不超过5次，分钟内不超过100次
                String data = null;
                try {
                    data = justApi.getSellerItem(justAppkey,justAppsecret,accessToken, modified_begin, modified_end,null ,page_index.toString());
                } catch (IOException e) {
                    e.printStackTrace();
                }
                org.json.JSONObject jsonObject = new org.json.JSONObject(data);
                if(jsonObject.get("code").toString().equals("0")) {
                    String data1 = jsonObject.get("data").toString();
                    JSONObject jsonObject1 = new JSONObject(data1);
                    if(Integer.parseInt(jsonObject1.get("data_count").toString()) > 0) {
                        if(jsonObject1.get("has_next").toString().equals("false")) {
                            has_next = false;
                        }
                        responseData = outOrderService.saveJstOutOrder(jsonObject1, user, byId);

                    } else {
                        has_next = false;
                        responseData.setSuccess(false);
                        responseData.setMessage("未获取到快递明细");
                    }
                } else {
                    has_next = false;
                    responseData.setSuccess(false);
                    responseData.setMessage("拉取失败！"+data);
                }

                page_index++;
                if(has_next) {
                    try {
                        Thread.currentThread().sleep(650);//如果有下一页 等待0.65秒
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }

            return responseData;
        }

    @Override
    public ResponseData submitJSTOutOrder(Long[] ids) {


        ResponseData data = new ResponseData();
        data.setSuccess(true);
        OutOrderParam param = new OutOrderParam();
        User user  = userService.getById(1922549817034559490L);
        lock.lock();//获取锁
        try {
            for (Long id : ids) {
                OutOrder outOrder = outOrderService.getById(id);
                if (!"待提交".equals(outOrder.getOutOrderStatus())&&!"撤回".equals(outOrder.getOutOrderStatus())) {
                    continue;
                }
                OutOrderDetailedParam outOrderDetailedParam = new OutOrderDetailedParam();
                outOrderDetailedParam.setDetailedOutNumber(outOrder.getOutOrderNumber());
                List<OutOrderDetailedResult> list = outOrderDetailedService.findListBySpec(outOrderDetailedParam);
                if (list.size()==0) {
                    data.setSuccess(false);
                    data.setMessage("请先添加商品明细");
                    return data;
                }
                //提交时间
                outOrder.setSubmitTime(new Date());
                //提交人名称
                outOrder.setSubmitterName(user.getName());
                BasicCustomer basicCustomer = basicCustomerService.getById(outOrder.getOutCustomerId());
                if(ToolUtil.isNotEmpty(basicCustomer.getOutorderconfirm()) && basicCustomer.getOutorderconfirm().equals("是")) {
                    storageOutDetailedService.checkStock(outOrder,data);//校验库存
                    if(!data.getSuccess()){
                        return data;
                    }
                } else {
                    storageOutDetailedService.outSingleHSHN(outOrder,data);//生成拣货单
                    if(!data.getSuccess()){
                        return data;
                    }

                    if(data.getCode( ) == 7527){
                        Map<String,List<Map<String,String>>> mapData  = (Map<String, List<Map<String, String>>>)data.getData();
                        List<Map<String, String>> kcbzlist = (List<Map<String, String>>)mapData.get("kcbzlist");
                        List<Map<String, String>> bhlist = (List<Map<String, String>>)mapData.get("bhlist");

                        for (Map<String, String> stringObjectMap : bhlist) {
                            replenishmentOrderService.generateReplenishmentOrder(stringObjectMap.get("goodsNumber"),stringObjectMap.get("goodsCount"));
                        }
                    }

                    StorageOutParam storageOutParam = new StorageOutParam();
                    storageOutParam.setStorageOutNumber(outOrder.getCustomerNumber());
                    StorageOutResult storageOutResult = storageOutService.findBySpec(storageOutParam);
                    if(ToolUtil.isEmpty(storageOutResult)){
                        continue;
                    }
                    List<StorageOutResult> listr = new ArrayList<StorageOutResult>();
                    listr.add(storageOutResult);
                    data = storageOutDetailedService.recommend(listr);//出库推荐库位 （~  . ~  ）***
                    if (!data.getSuccess()) {
                        return data;
                    }
                }

//                if(outOrder.getOutWay().equals("配送")){
//                    ToolUtil.copyProperties(outOrder,param);
//                    orderTransportService.outUpdateTransport(param);
//                    OrderTransportParam orderTransportParam = new OrderTransportParam();
//                    orderTransportParam.setCustomerOrder(param.getCustomerNumber());
//                    OrderTransportResult orderTransportResult = orderTransportService.findBySpec(orderTransportParam,null);
//                    if(orderTransportResult != null) {
//                        orderTransportService.auditorder(orderTransportResult.getId());
//                    }
//                }
//                param = new OutOrderParam();
//                outOrder = new OutOrder();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();//释放锁
        }
        return data;

    }
    @Autowired
    OutOrderController outOrderController;
    @Override
    public void autoCommitOrder(long l, long l1) {

        User user = userService.getById(l);
        OutOrderParam outOrderParam = new OutOrderParam();
        outOrderParam.setDeliverId(user.getDeliverId());
        outOrderParam.setDeptId(user.getDeptId());
        outOrderParam.setOutOrderStatus("list");

//        List<OutOrderResult> datalist = outOrderService.findListBySpec(outOrderParam,user.getOperateId());
        Page<OutOrderResult> outOrderResultPage = outOrderMapper.customPageList(new Page(1, 10), outOrderParam, "", user.getOperateId());
        List<OutOrderResult> records = outOrderResultPage.getRecords();
        List<Long> idList = new ArrayList<>();
        records.forEach(data -> {
            OutOrderResult outOrder = (OutOrderResult) data;
            if (!outOrder.getCustomerNumber().startsWith("A")) {
                Integer id = outOrder.getId();
                idList.add(Long.valueOf(id));
            }}
        );
//        idList.forEach(id -> {
//            ResponseData data = new ResponseData();
//            OutOrder outOrder = outOrderService.getById(id);
//
//        });
        submitJSTOutOrder(idList.toArray(new Long[idList.size()]));
    }

    @Override
    public void getJSTOutOrderWh(long userId, long customerId) {
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String modified_end = now.format(formatter);

        // 减去20分钟
        LocalDateTime tenMinutesAgo = now.minus(Duration.ofMinutes(20));
        String modified_begin = tenMinutesAgo.format(formatter);
            User user = userService.getById(userId);
            BasicCustomer byId = basicCustomerService.getById(customerId);
            String justAppsecret = byId.getJustAppsecret();
            String justAppkey = byId.getJustAppkey();
            String accessToken = byId.getAccessToken();

//		ApiResponse jstDdcx = JstDdcx.getJstDdcx(justAppkey, justAppsecret, accessToken,
//				null,modified_begin,modified_end);
//		System.out.println("jstDdcx:" + jstDdcx.toString());
//
//		ResponseData responseData = outOrderService.saveJstOutOrder(jstDdcx, user, byId);
            ResponseData responseData = new ResponseData();

            List<OrderPutExcelItem> list = new ArrayList<OrderPutExcelItem>();
            Integer page_index = 1;//页数
            boolean has_next = true;//是否有下一页
            while (has_next) {
                //只能分页查询，一页最多50条
                //接口调用频率秒级内不超过5次，分钟内不超过100次
                String data = null;
//			ApiResponse jstDdcx = null;
                try {
                    data = justApi.getWhSellerItem(justAppkey,justAppsecret,accessToken, modified_begin, modified_end,null ,page_index.toString());
                } catch (IOException e) {
                    e.printStackTrace();
                }
//			ObjectMapper mapper = new ObjectMapper();
//			try {
//				jstDdcx = mapper.readValue(data, ApiResponse.class);
//			} catch (IOException e) {
//				e.printStackTrace();
//			}
                org.json.JSONObject jsonObject = new org.json.JSONObject(data);
                if(jsonObject.get("code").toString().equals("0")) {
                    String data1 = jsonObject.get("data").toString();
                    JSONObject jsonObject1 = new JSONObject(data1);
                    if(Integer.parseInt(jsonObject1.get("data_count").toString()) > 0) {
                        if(jsonObject1.get("has_next").toString().equals("false")) {
                            has_next = false;
                        }
//                    responseData = outOrderService.saveJstOutOrder(jsonObject1, user, byId);
                        responseData = whOutOrderService.saveJstOutOrder(jsonObject1, user, byId);

                    } else {
                        has_next = false;
                        responseData.setSuccess(false);
                        responseData.setMessage("未获取到快递明细");
                    }
                } else {
                    has_next = false;
                    responseData.setSuccess(false);
                    responseData.setMessage("拉取失败！"+data);
                }

                page_index++;
                if(has_next) {
                    try {
                        Thread.currentThread().sleep(650);//如果有下一页 等待0.65秒
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
    }


    public static void main(String[] args) {

        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String nowStr = now.format(formatter);
        System.out.println(nowStr);

        // 减去10分钟
        LocalDateTime tenMinutesAgo = now.minus(Duration.ofMinutes(10));
        String tenMinutesAgoStr = tenMinutesAgo.format(formatter);
        System.out.println(tenMinutesAgoStr);

    }
}
